package com.ITArmy.service.impl;

import com.ITArmy.beans.Chapter;
import com.ITArmy.common.ServerResponse;
import com.ITArmy.dao.ChapterMapper;
import com.ITArmy.service.ChapterService;
import com.ITArmy.util.CheckMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service

public class ChapterServiceImpl implements ChapterService {
    @Autowired
    ChapterMapper chapterMapper;

    /**
     * 根据连载连载id添加章节（增）
     */
    @Override
    public ServerResponse addChapter(Chapter chapter) {
        chapter.setChTime(new Date());
        int resultCount = chapterMapper.insertSelective(chapter);
        CheckMessage check = new CheckMessage();
        return check.getMessage(resultCount, "添加成功", "添加失败");
    }

    /**
     * 根据连载连载id，和章节id删除指定的章节（删）
     */
    @Override
    public ServerResponse deleteChapter(long serializeId, long chapterId) {

        int resultCount = chapterMapper.deleteByTwoId(serializeId, chapterId);
        CheckMessage check = new CheckMessage();
        return check.getMessage(resultCount, "删除成功", "删除失败");
    }

    /**
     * 根据连载id和章节id修改章节内容（改）
     */
    @Override
    public ServerResponse amendChapter(Chapter chapter) {
        int resultCount = chapterMapper.updateByPrimaryKeySelective(chapter);
        CheckMessage check = new CheckMessage();
        return check.getMessage(resultCount, "修改成功", "修改失败");
    }

    /**
     * 根据连载id获取所有的章节（查）
     */
    @Override
    public ServerResponse getAllChapter(long serializeId) {
        List<Chapter> chapters = chapterMapper.selectBySerializeIdsss(serializeId);
        if (chapters.size() == 0) {
            return ServerResponse.createByErrorMesage("该书没有章节");
        }
        System.out.println(chapters);
        return ServerResponse.createBySuccess("获取到全部的章节", chapters);
    }

    /**
     * 根据章节id查找章节内容
     */
    @Override
    public ServerResponse getChapterByChid(long chid) {
        return ServerResponse.createBySuccess(chapterMapper.getChapterByChid(chid));
    }

    //上传章节信息

    @Override
    public ServerResponse insertSerialize(HttpServletRequest request, String ch_title, int ch_number, String ch_address, long sId) {
        Chapter chapter = new Chapter();
        chapter.setChTitle(ch_title);
        chapter.setChNumber(ch_number);
        chapter.setChAddress(ch_address);
        chapter.setChTime(new Date());
        chapter.setsId(sId);
        //查询一下该章节是否储存在
        if (chapterMapper.findChapter(ch_number, sId).size() > 0) {
            return ServerResponse.createByErrorMesage("您已经发表过该章节了");
        }
        chapterMapper.insert(chapter);
        return ServerResponse.createBySuccessMessage("发表成功...");
    }
}
